package com.soriya.nestlive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soriya.nestlive.common.GlobalThreadLocal;
import com.soriya.nestlive.constant.CommonConst;
import com.soriya.nestlive.entity.AdminEntity;
import com.soriya.nestlive.entity.param.LoginParam;
import com.soriya.nestlive.entity.vo.InfoVo;
import com.soriya.nestlive.mapper.AdminMapper;
import com.soriya.nestlive.service.AdminService;
import com.soriya.nestlive.util.RedisUtil;
import com.soriya.nestlive.util.ToolsUtil;
import com.soriya.nestlive.util.excpetion.MyException;
import org.springframework.stereotype.Service;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdminEntity> implements AdminService {
    @Override
    public String login(LoginParam login) {
        String username = login.getUsername();
        String password = login.getPassword();

        AdminEntity adminEntity = getOne(new LambdaQueryWrapper<AdminEntity>().eq(AdminEntity::getUsername, username));
        if (adminEntity == null) throw new MyException("用户名或密码错误");

        password = ToolsUtil.makeMd5(password + adminEntity.getSalt());

        if (!password.equals(adminEntity.getPassword())) throw new MyException("用户名或密码错误");

        String token = ToolsUtil.makeToken();

        RedisUtil.set(CommonConst.ADMIN_TOKEN_PREFIX + token, adminEntity.getId(), 60 * 60 * 24);

        return token;
    }

    @Override
    public InfoVo getInfo() {
        Long adminId = GlobalThreadLocal.getAdminId();

        System.out.println("adminId: " + adminId);

        AdminEntity admin = getById(adminId);
        if (admin == null) throw new MyException();

        InfoVo infoVo = new InfoVo();
        infoVo.setId(admin.getId());
        infoVo.setName(admin.getAdminName());
        infoVo.setAvatar(admin.getAvatar());
        return infoVo;
    }
}
